package memory

import (
	"errors"
	"io"

	"github.com/spf13/pflag"

	"gitee.com/bjf-fhe/apicat/entry"
	"gitee.com/bjf-fhe/apicat/entry/handler"
	"gitee.com/bjf-fhe/apicat/platform"
	"gitee.com/bjf-fhe/apicat/source"
)

type MemoryPlatform struct {
	entries chan *entry.LogEntry
	c       chan *entry.LogEntryResponse
}

func (p *MemoryPlatform) GetNotifier(ncfg *handler.Config) (platform.Notifier, error) {
	return nil, errors.New("not supported function")
}

func (p *MemoryPlatform) GetSource(fileHandler platform.Configer, tailMode bool) (source.Reader, error) {
	return p, nil
}

func (p *MemoryPlatform) AddFlags(set *pflag.FlagSet) {
}

func (p *MemoryPlatform) Records() chan *entry.LogEntryResponse {
	go func() {
		for e := range p.entries {
			if e != nil {
				p.c <- &entry.LogEntryResponse{Entry: e}
			} else {
				p.c <- &entry.LogEntryResponse{Error: &entry.LogError{
					Error:     io.EOF,
					MachineId: "memory",
				}}
				break
			}
		}
	}()
	return p.c
}

//New 创建一个内存平台,该平台主要用于测试，不提供init方法，需要手动调用New方法完成初始化并注册
func New(entries []*entry.LogEntry) *MemoryPlatform {
	var c = make(chan *entry.LogEntry, 1)
	var resendC = make(chan *entry.LogEntryResponse, 1)
	go func() {
		for _, e := range entries {
			c <- e
		}
		c <- nil
	}()
	var plat = &MemoryPlatform{
		entries: c,
		c:       resendC,
	}
	// platform.Register("memory", plat)
	return plat
}

//New 创建一个内存平台,提供一个chan从外部获得entry，不提供init方法，需要手动调用NewFlow方法完成初始化并注册
func NewFlow(entries chan *entry.LogEntry) *MemoryPlatform {
	var resendC = make(chan *entry.LogEntryResponse, 1)
	var plat = &MemoryPlatform{
		entries: entries,
		c:       resendC,
	}
	// platform.Register("memory", plat)
	return plat
}
